package com.xiaoke.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaoke.api.service.UserService;
import com.xiaoke.entity.User;
import com.xiaoke.util.common.AjaxMsg;
import com.xiaoke.util.common.ValidUtil;
import com.xiaoke.util.http.HttpUtils;
import com.xiaoke.util.weixin.AesCbcUtil;
import com.xiaoke.utils.SnowflakeIdWorker;
import com.xiaoke.utils.TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/user")
public class UserController {
    @Value("${wx.miniApp.appID}")
    private String APPID;
    @Value("${wx.miniApp.secret}")
    private String SECRET;
    @Autowired
    private UserService userService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @PostMapping("/login")
    @ResponseBody
    public AjaxMsg login(HttpServletRequest request, String code, String userInfo) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        String encryptedData, iv,rawData;
        Map userData = new HashMap();
        //根据code获取sessionKey
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String json = HttpUtils.getURLContent(url);
        if (!json.isEmpty()) {
            JSONObject jsonObject = JSON.parseObject(json);
            JSONObject userInfoObject = JSON.parseObject(userInfo);
            String sessionKey = jsonObject.getString("session_key");
            //尝试解密数据
            try {
                //用户信息
                String result = AesCbcUtil.decrypt(userInfoObject.getString("encryptedData"), sessionKey, userInfoObject.getString("iv"), "UTF-8");
                //如果解密结果不为空
                if (null != result && result.length() > 0 ) {
//                if (null != result && result.length() > 0) {

                    //转化为JSON
                    JSONObject userInfoJSON = JSON.parseObject(result);
                    String openId = userInfoJSON.getString("openId");
                    String city = userInfoJSON.getString("city");
                    String avatarUrl = userInfoJSON.getString("avatarUrl");
                    String nickName = userInfoJSON.getString("nickName");
                    String province = userInfoJSON.getString("province");
                    System.out.print("result:" + result);

                    //查询系统中是否有该用户
                    Map<String, Object> map = new HashMap<>();
                    map.put("weixinOpenid", openId);
                    List<User> users = userService.findByParams(map);
                    User user;
                    if (users != null && !users.isEmpty()) {
                        //系统中有该用户
                        user = users.get(0);
                        user.setAvatar(avatarUrl);
                        user.setNickName(nickName);
                        user.setProvince(province);
                        user.setCity(city);
                        user.setWeixinOpenid(openId);
                        String token = String.valueOf(TokenGenerator.generateValue());
                        user.setToken(token);
                        userService.update(user);

                        userData.put("userInfo", user);

                        ajaxMsg.setDatas(userData);
                    } else {
                        //系统中无该用户,则新建用户
                        user = new User();
                        String newUserId = String.valueOf(snowflakeIdWorker.nextId());
                        String token = String.valueOf(TokenGenerator.generateValue());
                        user.setId(newUserId);
                        user.setWeixinOpenid(openId);
                        user.setToken(token);
                        user.setCity(city);
                        user.setProvince(province);
                        user.setNickName(nickName);
                        user.setAvatar(avatarUrl);
                        userService.insert(user);

                        userData.put("userInfo", user);
                        ajaxMsg.setDatas(userData);
                    }
                } else {
                    //解密结果为空
                    ajaxMsg.setCode(AjaxMsg.FAILURE);
                    ajaxMsg.setMessage("微信登陆失败");
                    return ajaxMsg;
                }
            } catch (Exception e) {
                e.printStackTrace();
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("微信登陆失败");
                return ajaxMsg;
            }
        } else {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("微信登录失败");
            return ajaxMsg;
        }
        return ajaxMsg;
    }

}
